package mongo

import (
	"context"
	"stock_app/models"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func ListLog(name string, skip int64, limit int64) (logArr []*models.JobLog, err error) {
	logArr = make([]*models.JobLog, 0)
	// 过滤条件
	filter := &models.JobLogFilter{JobName: name}
	// 按照任务开始时间倒排
	logSort := &models.SortLogByStartTime{SortOrder: -1}
	logCollection := mongodb.Database("cron").Collection("log")
	var cursor *mongo.Cursor
	if cursor, err = logCollection.Find(context.TODO(), filter, &options.FindOptions{Sort: logSort, Skip: &skip, Limit: &limit}); err != nil {
		return
	}
	// 延迟释放游标
	defer cursor.Close(context.TODO())

	for cursor.Next(context.TODO()) {
		jobLog := &models.JobLog{}
		// 反序列化BSON
		if err = cursor.Decode(jobLog); err != nil {
			continue // 有日志不合法
		}

		logArr = append(logArr, jobLog)
	}
	return

}
